#!/usr/bin/perl

#------------------------------------------------------------#
# Program to bin the SS433 photometric data in all_sort.dat  #
# in various ways.                                           #
#                                             Bmort  31Jan07 #
#------------------------------------------------------------#

system("clear");

print "===================================================\n";
print "\tData binning for SS433 data\n";
print "\t(for help see binning.readme)\n";
print "===================================================\n";

# GET COMMAND ARGS FOR FILE NAMES
$numArgs = $#ARGV + 1;
if ($numArgs != 2) {
    message("ERROR: Incorect number of command line args");
    messageLine();
    usage();
    exit(1);
}

$dataFileName = $ARGV[0];
$outFile = $ARGV[1];
message("Input data file = \"$dataFileName\"");
message("Output file root= \"$outFile\"");
messageLine();

# OPEN DATA FILE AND STORE IN ARRAY OF RAW DATA
use Cwd;
$dir = getcwd(); # Where am I?
open(DATA, $dataFileName);
@lines = <DATA>; # read data file into an array
close(DATA);

# EXTRACT RAW DATA INTO USEFUL ARRAYS
#====================================
$i=0;
$lskip = 0; # fix for blank lines
@ObsTime;
@ObsMag;
foreach $line (@lines) {
    if ($line =~ /^\s+/) { print "** "; $lskip++;}
    $line =~ m/^(\d+\.\d+|\d+)\s+(\d+\.\d+|\d+)/;
    $ObsTime[$i] = $1;
    $ObsMag[$i]  = $2;
    $i++;
}


# GET SOME INFO ON THE DATA
#==========================
$dataLength = $i-$lskip;
message("Data Length (# samples) = $dataLength");
$ObsTimeRange = $ObsTime[$dataLength-1]-$ObsTime[0];
message("Obs. time range ($ObsTime[0] to $ObsTime[$dataLength-1]) = $ObsTimeRange");
messageLine();

# GET BINNING PARAMETERS (FROM STDIN - USER PROMTEDED)
#=====================================================

#prompt user for inputs 
#messageLine();
$binLength = &promptUser("* Enter bin length (days), ",
			 int $ObsTimeRange/5);
#$binOverlap = &promptUser("* Enter bin overlap (days), ",0);
#$binStartOffset = &promptUser("* Enter bin start offset (days), ",0);
#print summary
message();
message("Bin length  = $binLength");
#sub_message("Bin overlap = $binOverlap");
#sub_message("Bin start offset = $binStartOffset");
 

#check for some simple errors in imputs
if ($binOverlap >= $binLength) {
    messageLine();
    message("ERROR: Bin overlap longer than bin length, check options!");
    exit(3);
}

message();
message();
messageLine();
for ($binOverlap =0;$binOverlap<$binLength;$binOverlap++) {
message("Overlap = $binOverlap (l=$binLength)");

# (SIMPLE BINNING) GET NUMBER OF BINS
#====================================
# no. bins = (range - offset)/(bin length - overlap) - overlap + 1
$range = $ObsTimeRange-$binStartOffset+1;
#print "--> range: $range\n";
#$length = $binLength;
$overlap = $binOverlap;
#$nOverlaps = int $range/$binLength; #no of bins that fit in the range
#$total_overlap = $nOverlaps*$overlap;

#$fractNumBins = ($range + $total_overlap)/$binLength;
$fractNumBins = ($range-$overlap)/($binLength-$overlap);
$intNumBins = int $fractNumBins;
$test = $fractNumBins - ($range)/($binLength-$overlap);
if ($overlap != 0) {$test2 = $test/$overlap;}
#essageLine();
#essage("Fractional number of bins  = $fractNumBins");   
message("bins  = $intNumBins");   
message("test  = $test");
message("test2 = $test2");
#    message("Total overlap length       = $total_overlap");
if ($intNumBins < 1) {
    message();
	message("ERROR: No full length bins fit in the data set, check options!");
    exit(3);
}
messageLine();


}





















#################################################

sub usage()
{
    print "-\n";
    print "- USAGE: []\$ perl dataBinning.pl [DATAFILENAME] [OUTNAME_ROOT]\n";
    print "-\n";
}

sub message {
    my $messageString = shift;
    print "- $messageString\n";
}

sub messageLine {
    print "---------------------------------------------------\n";
}


sub sub_message {
    my $messageString = shift;
    print "-   $messageString\n";
}

sub title_message {
    my $messageString = shift;
    print "= $messageString\n";
}


sub promptUser {
    
    #-------------------------------------------------------------------#
    #  two possible input arguments - $promptString, and $defaultValue  #
    #  make the input arguments local variables.                        #
    #-------------------------------------------------------------------#
    
    local($promptString,$defaultValue) = @_;
    
    #-------------------------------------------------------------------#
    #  if there is a default value, use the first print statement; if   #
    #  no default is provided, print the second string.                 #
    #-------------------------------------------------------------------#
    
    
    if ($defaultValue || $defaultValue == 0) {
        print $promptString, "[", $defaultValue, "]: ";
    } else {
        print $promptString, ": ";
    }

    $| = 1;               # force a flush after our print
    $_ = <STDIN>;         # get the input from STDIN (presumably the keyboard)


    #------------------------------------------------------------------#
    # remove the newline character from the end of the input the user  #
    # gave us.                                                         #
    #------------------------------------------------------------------#

    chomp;

    #-----------------------------------------------------------------#
    #  if we had a $default value, and the user gave us input, then   #
    #  return the input; if we had a default, and they gave us no     #
    #  no input, return the $defaultValue.                            #
    #                                                                 # 
    #  if we did not have a default value, then just return whatever  #
    #  the user gave us.  if they just hit the <enter> key,           #
    #  the calling routine will have to deal with that.               #
    #-----------------------------------------------------------------#

    if ("$defaultValue" || $defaultValue == 0) {
        return $_ ? $_ : $defaultValue;    # return $_ if it has a value
    } else {
        return $_;
    }
}
